package com.lisx.module_matters.dialogfragment;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.ToastUtils;
import com.fenghuajueli.lib_data.constants.EventBusConstants;
import com.fenghuajueli.lib_data.entity.db.MattersDbEntity;
import com.fenghuajueli.lib_data.entity.eventbus.EventEntity;
import com.fenghuajueli.libbasecoreui.manager.MattersManager;
import com.ijianji.lsx_ui_lib.BaseDialogFragment;
import com.lisx.module_matters.R;
import com.lisx.module_matters.utils.TimeUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.Calendar;
import java.util.Date;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class AddMattersDialogFragment extends BaseDialogFragment implements View.OnClickListener {

    TimePickerView pvCustomLunar;
    private TextView tvStartTime;
    private TextView tvEndTime;
    boolean isSelectTime = true;
    private MattersDbEntity mattersDbEntity;
    private EditText etName, etDesc;
    int type = 1;

    @Override
    public int getLayoutRes() {
        return R.layout.dialog_fragment_add_matters;
    }

    @Override
    public void initView(Context context, View view, AttributeSet attributeSet) {
        initDate(context);
        mattersDbEntity = new MattersDbEntity();
        tvStartTime = view.findViewById(R.id.tv_start_time);
        tvEndTime = view.findViewById(R.id.tv_end_time);
        etName = view.findViewById(R.id.et_name);
        etDesc = view.findViewById(R.id.et_desc);
        tvEndTime = view.findViewById(R.id.tv_end_time);
        tvStartTime.setOnClickListener(this);
        tvEndTime.setOnClickListener(this);
        view.findViewById(R.id.tv_complete).setOnClickListener(this);
    }

    @Override
    public void initData(Context context) {

    }

    @Override
    public void initEvent(Context context) {

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_start_time) {
            pvCustomLunar.show();
            isSelectTime = true;
        } else if (v.getId() == R.id.tv_end_time) {
            isSelectTime = false;
            pvCustomLunar.show();
        } else if (v.getId() == R.id.tv_complete) {
            save();
        }
    }

    private void save() {
        String mattersName = etName.getText().toString().trim();
        String desc = etDesc.getText().toString().trim();
        if (TextUtils.isEmpty(mattersName)) {
            ToastUtils.showShort("请输入事项名称");
            return;
        }
        if (mattersDbEntity.getStart_time() == 0) {
            ToastUtils.showShort("请选择开始时间");
            return;
        }
        if (mattersDbEntity.getEnd_time() == 0) {
            ToastUtils.showShort("请选择结束时间");
            return;
        }
        if (mattersDbEntity.getEnd_time() <= mattersDbEntity.getStart_time()) {
            ToastUtils.showShort("请选择正确的开始时间和结束时间!");
            return;
        }
        mattersDbEntity.setCreate_time(System.currentTimeMillis());
        mattersDbEntity.setMatters_name(mattersName);
        if (!TextUtils.isEmpty(desc)) {
            mattersDbEntity.setDesc(desc);
        }
        mattersDbEntity.setType(type);
        Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Boolean> emitter) throws Exception {
                MattersManager.getInstance().saveMattersDbEntity(mattersDbEntity);
                emitter.onNext(true);
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull Boolean aBoolean) {
                        EventBus.getDefault().post(new EventEntity(EventBusConstants.UPDATE_MATTERS));
                        ToastUtils.showShort("添加成功");
                        dismiss();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        ToastUtils.showShort("失败");
                        dismiss();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void initDate(Context context) {
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(1900, 0, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2099, 11, 30);
        //时间选择器 ，自定义布局
        pvCustomLunar = new TimePickerBuilder(context, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                if (isSelectTime) {
                    mattersDbEntity.setStart_time(date.getTime());
                    tvStartTime.setText(TimeUtils.getParseDayTextTime2(date));
                } else {
                    mattersDbEntity.setEnd_time(date.getTime());
                    tvEndTime.setText(TimeUtils.getParseDayTextTime2(date));
                }
//                countDownBean.setDate(date.getTime());
            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_lunar, new CustomListener() {

                    @Override
                    public void customLayout(final View v) {
                        TextView tvCancel = (TextView) v.findViewById(R.id.tv_cancel);
                        TextView tvConfirm = (TextView) v.findViewById(R.id.tv_confirm);
                        tvCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomLunar.dismiss();
                            }
                        });
                        tvConfirm.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                pvCustomLunar.returnData();
                                pvCustomLunar.dismiss();
                            }
                        });

                    }
                })
                .setType(new boolean[]{true, true, true, true, true, true})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(Color.RED)
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isDialog(true)//是否显示为对话框样式
                .build();
    }

    public void setType(int type) {
        this.type = type;
    }

}
